# coding= utf-8
from pexpect import pxssh


class serverAccess:
    def __init__(self, host, usr, psw):
        self.__host = host
        self.__usr = usr
        self.__psw = psw
        self.session = None

    def login(self, prompt):
        ssh = pxssh.pxssh()
        ssh.login(self.__host, self.__usr, self.__psw, original_prompt=prompt, auto_prompt_reset=False)
        if ssh.isalive() and ssh.isatty():
            ssh.PROMPT = prompt
            self.session = ssh
            return ssh
        else:
            raise Exception("login is not active")

    def execmd(self, cmd):
        self.session.buffer = ''
        self.session.sendline(cmd)
        self.session.prompt()
        res = str(self.session.before) + str(self.session.after)
        return res

    def exeinteractivecmd(self, cmd, prompt, cmd2, prompt2):
        self.session.buffer = ''
        self.session.sendline(cmd)
        index = self.session.expect(prompt)
        if index == 0:
            self.session.sendline(cmd2)
            index = self.session.expect(prompt2)
            if index == 0:
                res = str(self.session.before) + str(self.session.after)
                return res
            else:
                raise Exception("exec cmd error in when execute " + cmd2)
        else:
            raise Exception("exec cmd error in when execute " + cmd)

    def logout(self):
        if self.session is not None:
            self.session.logout()
